package frontend.admin;

import backend.DiseaseItem;
import backend.GeneralDatabase;
import backend.PermissionDenied;
import service.DatabaseManager;

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
public class DiseaseTableComponents {
    private final JTable table;
    private final JScrollPane scrollPane;
    private final DiseaseTableModel tableModel;

    public DiseaseTableComponents() {
        // 初始化模型和表格
        tableModel = new DiseaseTableModel();
        table = new JTable(tableModel);
        table.setRowHeight(30);
        table.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        table.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 15));

        // 设置操作列渲染器和编辑器
        ActionButtonsRendererEditor buttonsRenderer = new ActionButtonsRendererEditor();
        table.getColumnModel().getColumn(9).setCellRenderer((table, value, isSelected, hasFocus, row, column) ->
                buttonsRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column));
        table.getColumnModel().getColumn(9).setCellEditor(buttonsRenderer);

        // 滚动面板
        scrollPane = new JScrollPane(table);
    }

    public JScrollPane getScrollPane() {
        return scrollPane;
    }

    public void addDisease(DiseaseItem disease) {
        tableModel.addDisease(disease);
    }


    // 自定义表格模型
    private static class DiseaseTableModel extends AbstractTableModel {
        private final String[] columnNames = {"疾病名称", "症状", "发生部位", "药物治疗", "缓解方式", "饮食建议", "影响程度", "紧急程度", "科室","操作"};
        private final List<Disease> diseases = new ArrayList<>();

        public DiseaseTableModel() {
            try {
                GeneralDatabase db = DatabaseManager.getInstance();
                DiseaseItem[] items = db.queryDiseases("");
                for (DiseaseItem item : items) {
                    diseases.add(new Disease(
                            item.Cause(),
                            item.Symptom(),
                            item.Organ(),
                            item.Medication(),
                            item.Reliefmethod(),
                            item.Diet(),
                            item.Impact(),
                            item.Urgency(),
                            item.Department()
                    ));
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "加载疾病数据失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        }

        public void addDisease(DiseaseItem disease) {
            diseases.add(new Disease(
                    disease.Cause(),
                    disease.Symptom(),
                    disease.Organ(),
                    disease.Medication(),
                    disease.Reliefmethod(),
                    disease.Diet(),
                    disease.Impact(),
                    disease.Urgency(),
                    disease.Department()
            ));
            fireTableRowsInserted(diseases.size() - 1, diseases.size() - 1);
        }

        public void updateDisease(int rowIndex, DiseaseItem item) {
            if (rowIndex >= 0 && rowIndex < diseases.size()) {
                Disease disease = diseases.get(rowIndex);
                disease.name = item.Cause();
                disease.symptom = item.Symptom();
                disease.organ = item.Organ();
                disease.medication = item.Medication();
                disease.reliefMethod = item.Reliefmethod();
                disease.diet = item.Diet();
                disease.impact = item.Impact();
                disease.urgency = item.Urgency();
                fireTableCellUpdated(rowIndex, rowIndex);
            }
        }

        public void removeDisease(int rowIndex) {
            if (rowIndex >= 0 && rowIndex < diseases.size()) {
                diseases.remove(rowIndex);
                fireTableRowsDeleted(rowIndex, rowIndex);
            }
        }

        @Override
        public int getRowCount() {
            return diseases.size();
        }

        @Override
        public int getColumnCount() {
            return columnNames.length;
        }

        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }

        @Override
        public Object getValueAt(int row, int col) {
            Disease disease = diseases.get(row);
            switch (col) {
                case 0: return disease.name;
                case 1: return disease.symptom;
                case 2: return disease.organ;
                case 3: return disease.medication;
                case 4: return disease.reliefMethod;
                case 5: return disease.diet;
                case 6: return disease.impact;
                case 7: return disease.urgency;
                case 8: return disease.department;
                case 9: return "操作";
                default: return null;
            }
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return column == 9;
        }

        @Override
        public Class<?> getColumnClass(int columnIndex) {
            return columnIndex == 9 ? JButton.class : Object.class;
        }

        // 疾病数据模型
        private static class Disease {
            String name, symptom, organ, medication, reliefMethod, diet, impact, urgency,department;

            Disease(String name, String symptom, String organ, String medication, String reliefMethod, String diet, String impact, String urgency,String department) {
                this.name = name;
                this.symptom = symptom;
                this.organ = organ;
                this.medication = medication;
                this.reliefMethod = reliefMethod;
                this.diet = diet;
                this.impact = impact;
                this.urgency = urgency;
                this.department = department;
            }
        }
    }

    // 操作列渲染器与编辑器
    private class ActionButtonsRendererEditor extends AbstractCellEditor implements TableCellRenderer, TableCellEditor {
        private final JButton editButton = new JButton("修改");
        private final JButton deleteButton = new JButton("删除");
        private final JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
        private int currentRow = -1;
        GeneralDatabase db;

        public ActionButtonsRendererEditor() {
            setupButton(editButton, new Color(144, 238, 144), Color.WHITE); // 绿色
            setupButton(deleteButton, new Color(255, 99, 71), Color.WHITE); // 红色
            panel.add(editButton);
            panel.add(deleteButton);

            // 按钮事件绑定
            editButton.addActionListener(e -> {
                DiseaseTableModel.Disease disease = tableModel.diseases.get(currentRow);
                DiseaseItem item = new DiseaseItem()
                        .Cause(tableModel.diseases.get(currentRow).name)
                        .Symptom(tableModel.diseases.get(currentRow).symptom)
                        .Organ(tableModel.diseases.get(currentRow).organ)
                        .Medication(tableModel.diseases.get(currentRow).medication)
                        .Reliefmethod(tableModel.diseases.get(currentRow).reliefMethod)
                        .Diet(tableModel.diseases.get(currentRow).diet)
                        .Impact(tableModel.diseases.get(currentRow).impact)
                        .Urgency(tableModel.diseases.get(currentRow).urgency)
                        .Department(tableModel.diseases.get(currentRow).department); // 添加 department 字段

                SwingUtilities.invokeLater(() -> {new AddDiseaseDialog((JFrame) SwingUtilities.getWindowAncestor(table), item, updatedItem -> {
                    try {
                        db = DatabaseManager.getInstance();

                        // 3. 删除原记录
                        String delResult = db.tryItemdel("admin", item);
                        if (!"SUCCESS".equals(delResult)) {
                            JOptionPane.showMessageDialog(null, "删除原记录失败: " + delResult);
                            return;
                        }

                        // 4. 新增修改后的记录
                        String addResult = db.tryItemadd("admin", updatedItem);
                        if ("SUCCESS".equals(addResult)) {
                            // 5. 更新表格显示
                            tableModel.removeDisease(currentRow); // 移除旧记录
                            tableModel.addDisease(updatedItem);   // 添加新记录
                        } else {
                            JOptionPane.showMessageDialog(null, "新增记录失败: " + addResult);
                            // 可选：回滚删除操作
                            db.tryItemadd("admin", item);
                        }
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, "操作失败: " + ex.getMessage());
                    }
                }).setVisible(true);
            });
            });
            deleteButton.addActionListener(e -> {
                if (JOptionPane.showConfirmDialog(null, "确定删除该疾病？") == JOptionPane.OK_OPTION) {
                    DiseaseItem item = new DiseaseItem()
                            .Cause(tableModel.diseases.get(currentRow).name)
                            .Symptom(tableModel.diseases.get(currentRow).symptom)
                            .Organ(tableModel.diseases.get(currentRow).organ)
                            .Medication(tableModel.diseases.get(currentRow).medication)
                            .Reliefmethod(tableModel.diseases.get(currentRow).reliefMethod)
                            .Diet(tableModel.diseases.get(currentRow).diet)
                            .Impact(tableModel.diseases.get(currentRow).impact)
                            .Urgency(tableModel.diseases.get(currentRow).urgency)
                            .Department(tableModel.diseases.get(currentRow).department); // 添加 department 字段

                    try {
                        db = DatabaseManager.getInstance();
                        String result = db.tryItemdel("admin", item); // 假设管理员用户名为 admin
                        if ("SUCCESS".equals(result)) {
                            tableModel.removeDisease(currentRow);
                        } else {
                            JOptionPane.showMessageDialog(null, "删除失败: " + result);
                        }
                    } catch (PermissionDenied ex) {
                        JOptionPane.showMessageDialog(null, "权限不足，无法删除疾病");
                    } catch (Exception ex) {
                        JOptionPane.showMessageDialog(null, "删除失败: " + ex.getMessage());
                    }
                }
                fireEditingStopped();
            });
        }

        private void setupButton(JButton button, Color bgColor, Color fgColor) {
            button.setBackground(bgColor);
            button.setForeground(fgColor);
            button.setFocusPainted(false);        // 禁用焦点边框
            button.setBorderPainted(false);       // 禁用边框绘制
            button.setContentAreaFilled(false);   // 防止默认背景干扰
            button.setOpaque(true);               // 确保颜色可以正确渲染
            button.setRolloverEnabled(false);     // 禁用悬停效果
            button.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            currentRow = row;

            // 强制设置按钮颜色，避免受表格选中状态影响
            editButton.setBackground(new Color(144, 238, 144)); // 绿色
            deleteButton.setBackground(new Color(255, 99, 71)); // 红色

            // 设置 panel 背景色与表格一致
            panel.setBackground(table.getBackground());

            return panel;
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
            currentRow = row;

            // 同样重置按钮颜色，避免编辑状态下颜色变化
            editButton.setBackground(new Color(144, 238, 144));
            deleteButton.setBackground(new Color(255, 99, 71));

            // 设置 panel 背景色与表格一致
            panel.setBackground(table.getBackground());

            return panel;
        }

        @Override
        public Object getCellEditorValue() {
            return null;
        }


    }
}
